//
//  XJChouxueViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/16.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "XJChouxueViewController.h"
#import "XJThirdViewController.h"
#import "XQSecondStepViewController.h"
@interface XJChouxueViewController ()

@end

@implementation XJChouxueViewController
static const NSString * KEY_STEP  = @"step2";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _currentStep = self.NewRecordArray.firstObject.savedStepCount + 1;
    _keyStepStr = [NSString stringWithFormat:@"step%ld", _currentStep];
    NSLog(@"setp%ld record === %@", _currentStep, self.NewRecordArray.firstObject.getDetailDict);
    
    [self setNaviBarTitle:self.NewRecordArray.firstObject.name];
    _contentTableView = [[UITableView alloc] initWithFrame:
                         CGRectMake(10, fHeight_Nav + fHeight_StatueBar + 10, fWidth_Current - 20, fHeight_Current - fHeight_Nav - fHeight_StatueBar - 60)];
    _contentTableView.backgroundColor = [UIColor clearColor];
    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _contentTableView.dataSource = self;
    _contentTableView.delegate = self;
    [self.view addSubview:_contentTableView];
    
    UIImageView*buttomview = [[UIImageView alloc]initWithFrame:CGRectMake(0, fHeight_Current - 50, fWidth_Current, 50)];
    buttomview.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    [self.view addSubview:buttomview];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 50)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:14];
    label.textColor=[UIColor lightGrayColor];
    label.text= [NSString stringWithFormat:@"当下是第%ld/%ld步",
                 (long)self.NewRecordArray.firstObject.savedStepCount + 1, (long)self.NewRecordArray.firstObject.allStepCount];
    [buttomview addSubview:label];
    timeArr=[[NSMutableArray alloc]init];
    for (Record *nowRecord in self.NewRecordArray) {
        NSString*timestr=@"";
        if ([[nowRecord getDetailDict] objectForKey:KEY_STEP] &&
            [[[nowRecord getDetailDict] objectForKey:KEY_STEP] count] > 0 &&
            [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:0] objectForKey:KEY_RECORD_ANSWER]) {
            timestr = [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:0] objectForKey:KEY_RECORD_ANSWER];
        }
       
        [timeArr addObject:timestr];
    }

}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1+self.NewRecordArray.count;

    }else{
        return 1;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;//返回标题数组中元素的个数来确定分区的个数
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return 60;
        }else{
            return 90;
        }
    }else{
        return 60;
    }
  
 
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *strIdentifier = [NSString stringWithFormat:@"strIdentifier%ld",(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];
    
    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                  reuseIdentifier:strIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            UILabel *titlelab = [[UILabel alloc]initWithFrame:
                                 CGRectMake(10, 0, fWidth_Current - 40, 60)];
            titlelab.textColor=[UIColor whiteColor];
            titlelab.backgroundColor=[UIColor clearColor];
            titlelab.text=@"2、抽血日期和时间";
            [cell addSubview:titlelab];
            
//            UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 59, fWidth_Current-20, 1)];
//            lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
//            [cell addSubview:lineview];
        }else{
            Record*nowrecord=[self.NewRecordArray objectAtIndex:indexPath.row-1];
            UILabel*recordNameLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, fWidth_Current, 30)];
            recordNameLab.backgroundColor=[UIColor clearColor];
            recordNameLab.textColor=[UIColor whiteColor];
            recordNameLab.font=[UIFont systemFontOfSize:16];
            recordNameLab.text=[NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
            [cell addSubview:recordNameLab];
            NSString*timestr=[timeArr objectAtIndex:indexPath.row-1];
            UILabel*timelab = [[UILabel alloc]initWithFrame:
                               CGRectMake(10, 30, tableView.frame.size.width - 52, 60)];
            timelab.backgroundColor = [UIColor clearColor];
            timelab.textColor = [UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            [cell addSubview:timelab];
            timelab.text=timestr;
            UIImageView *detailImageView = [[UIImageView alloc] initWithFrame:
                                            CGRectMake(timelab.frame.origin.x + timelab.frame.size.width+20,
                                                       timelab.frame.origin.y + (timelab.frame.size.height - 12) / 2 ,
                                                       12, 12)];
            detailImageView.image = [UIImage imageNamed:@"navleft"];
            [cell addSubview:detailImageView];
            UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current-20, 1)];
            lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
            [cell addSubview:lineview];
            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                detailImageView.hidden = YES;
            }else{
                detailImageView.hidden = NO;
            }
        }
        
    }else{
        cell.backgroundColor=[UIColor clearColor];

        UIView *footerView = [[UIView alloc] initWithFrame:
                              CGRectMake(0, 0, tableView.frame.size.width , 50)];
        footerView.backgroundColor = [UIColor clearColor];
        
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            
            UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 10, footerView.frame.size.width, 50)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"下一步" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            [cell addSubview:footerView];

        }else{
            
            UIButton *btn1=[[UIButton alloc]initWithFrame:
                            CGRectMake(0, 10, (footerView.frame.size.width - 10) / 2, 50)];
            btn1.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
            btn1.layer.cornerRadius=5;
            [btn1 setTitle:@"取消" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
            btn1.clipsToBounds=YES;
            [footerView addSubview:btn1];
            UIButton *btn2=[[UIButton alloc]initWithFrame:
                            CGRectMake(btn1.frame.origin.x + btn1.frame.size.width + 10,
                                       btn1.frame.origin.y,
                                       btn1.frame.size.width, btn1.frame.size.height)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"保存" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            [cell addSubview:footerView];

        }
    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 1.0f;
        
    
}

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *footerView = [[UIView alloc] initWithFrame:
                          CGRectMake(0, 0, tableView.frame.size.width , 1)];
    footerView.backgroundColor = [UIColor clearColor];
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
        
    }else{
        if (indexPath.section==0) {
            nowRow=indexPath.row-1;
            if (!_datePickAlertVC) {
                _datePickAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
                //初始化一个标题为“选择时间”，风格是ActionSheet的UIAlertController，其中"\n"是为了给DatePicker腾出空间
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    //点击确定按钮的事件处理
                    NSString*timestr = [self dateToString:_datePicker.date];
                    [timeArr replaceObjectAtIndex:nowRow withObject:timestr];
                    [tableView reloadData];
//                    _dateLabel.text = [self dateToString:_datePicker.date];
                }];
                
                _datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker
                _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
                [_datePickAlertVC.view addSubview:_datePicker];//将datePicker添加到UIAlertController实例中
                [_datePickAlertVC addAction:cancel];//将确定按钮添加到UIAlertController实例中
            }
            [self presentViewController:_datePickAlertVC animated:YES completion:^{
            }];//通过模态视图模式显示UIAlertController，相当于UIACtionSheet的show方法
        }
    }    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)saveClick{

    for (int i=0;i<timeArr.count;i++) {
        NSString*str=[timeArr objectAtIndex:i];
        if ([str isEqualToString:@""]) {
            Record*nowrecord=[self.NewRecordArray objectAtIndex:i];
            NSString*msg=[NSString stringWithFormat:@"请选择样本%@的采集日期！",nowrecord.recordId];
            [self.view makeToast:msg];
            return;
        }
    }
    [self creatDetailDict];
   
    if (self.NewRecordArray.firstObject.type==TYPE_RECORD_XUEQINGYANGBEN) {
        XQSecondStepViewController *XQSecondStepVC = [[XQSecondStepViewController alloc] init];
        XQSecondStepVC.NewRecordArray = self.NewRecordArray;
        [self.navigationController pushViewController:XQSecondStepVC animated:YES];

    }else if(self.NewRecordArray.firstObject.type==TYPE_RECORD_XUEJIANGYANGBEN) {
        XJThirdViewController *XJSecondStepVC = [[XJThirdViewController alloc] init];
        XJSecondStepVC.NewRecordArray = self.NewRecordArray;
        [self.navigationController pushViewController:XJSecondStepVC animated:YES];
    }

}
-(void)cancelclick{
    UIViewController*miloViewControl=(UIViewController *)[[self.navigationController viewControllers]objectAtIndex:1];
    [self.navigationController popToViewController:miloViewControl animated:YES];
}
- (NSString *)dateToString:(NSDate *)date {
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+0800"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    
    [formatter setTimeZone:timeZone];
    
    NSString * timeString = [formatter stringFromDate:date];
    
    return timeString;
}

-(void)creatDetailDict{
    for (Record *oneRecord in self.NewRecordArray) {
        NSInteger index =[self.NewRecordArray indexOfObject:oneRecord];
        NSString *timestr=[timeArr objectAtIndex:index];
        NSDictionary *questionDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"2.1、抽血日期和时间", KEY_RECORD_QUESTION,
                                      TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                      timestr, KEY_RECORD_ANSWER, nil];
        
        
        NSArray *qustionArr = [NSArray arrayWithObjects:questionDict, nil];
        
        NSMutableDictionary *tempDict = [oneRecord getDetailDict];
        [tempDict setObject:qustionArr forKey:KEY_STEP];
        [oneRecord setDetailDict:tempDict];
        oneRecord.recordDetail = [tempDict JSONString];
        oneRecord.savedStepCount = 2;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [oneRecord update];
        });
    }
}
    

-(void)nextStepClick{
    for (Record *oneRecord in self.NewRecordArray) {
        oneRecord.savedStepCount = 2;
    }

    if (self.NewRecordArray.firstObject.type==TYPE_RECORD_XUEQINGYANGBEN) {
        XQSecondStepViewController *XQSecondStepVC = [[XQSecondStepViewController alloc] init];
        XQSecondStepVC.NewRecordArray = self.NewRecordArray;
        XQSecondStepVC.fromtype = @"search";
        [self.navigationController pushViewController:XQSecondStepVC animated:YES];
        
    }else if(self.NewRecordArray.firstObject.type==TYPE_RECORD_XUEJIANGYANGBEN) {
        XJThirdViewController *XJSecondStepVC = [[XJThirdViewController alloc] init];
        XJSecondStepVC.NewRecordArray = self.NewRecordArray;
        XJSecondStepVC.fromtype = @"search";
        [self.navigationController pushViewController:XJSecondStepVC animated:YES];
    }
}

@end
